package vn.sms.lazylove;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import vn.sms.lazylove.database.DataStore;
import vn.sms.lazylove.object.OneSMS;
import vn.sms.lazylove.object.SchedulerSMSItem;
import vn.sms.lazylove.object.SendSms;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

	final public static String ONE_TIME = "onetime";
	int i = 0;
	DataStore mDataStore = DataStore.getInstance();
	NotificationManager mNM;

	@Override
	public void onReceive(Context context, Intent intent) {
		PowerManager pm = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(
				PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
		// Acquire the lock
		wl.acquire();
		try {
			// You can do the processing here.
			// mCreatSMS = new CreateSmsActivity();
			// mDataStore = DataStore.getInstance();
			List<SchedulerSMSItem> listSMS = mDataStore.getListSMSScheduler();
			List<OneSMS> listOneSMS = mDataStore.getListWeekOneSMS();
			SchedulerSMSItem smsItem = listSMS.get(0);
			OneSMS os = new OneSMS(1, 100, 0);
			if (listOneSMS.size() < 1) {
				mDataStore.addWeekOneSMS(os);
			} else {
				os = listOneSMS.get(0);
			}
			boolean flag = checkTimeSMS(smsItem, os);
			if (flag) {
				String phonenumber = smsItem.phone;
				String messagebody = smsItem.message;
				if (phonenumber.length() > 0 && messagebody.length() > 0) {
					String del = ",";
					String[] user = phonenumber.split(del);
					int index = user.length;
					for (int i = 0; i < index; i++) {
						sendSMS3(context, user[i], messagebody);
					}
					// save sms
					Format formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
					String time = formatter.format(new Date());
					SendSms sendsms = new SendSms(1, messagebody, phonenumber,
							time);
					mDataStore.addSendSMS(sendsms);
					// creat notifile
					//showNotification(context, smsItem);
					Intent myIntent = new Intent(context.getApplicationContext(),
							DemoActivity.class);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(myIntent);
				}
			}
		} catch (Exception ex) {
			// Toast.makeText(context, "Error Receive.",
			// Toast.LENGTH_LONG).show();
		}
		// Release the lock
		wl.release();
	}

	public void SetAlarm(Context context, SchedulerSMSItem smsItem) {
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
		Bundle b = new Bundle();
		b.putSerializable("smsItem", smsItem);
		intent.putExtras(b);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
				1000 * 59, pi);
	}

	public boolean checkTimeSMS(SchedulerSMSItem smsItem, OneSMS os) {
		try {
			String[] week = smsItem.week.split(",");
			String[] time = smsItem.time.split("-");
			String[] hour0 = time[0].split(":");
			String[] hour1 = time[1].split(":");

			Date d = new Date();
			Calendar calendar = Calendar.getInstance();
			int day = calendar.get(Calendar.DAY_OF_WEEK);
			String today = null;
			if (day == 2) {
				today = "Monday";
			} else if (day == 3) {
				today = "Tuesday";
			} else if (day == 4) {
				today = "Wednesday";
			} else if (day == 5) {
				today = "Thursday";
			} else if (day == 6) {
				today = "Friday";
			} else if (day == 7) {
				today = "Saturday";
			} else if (day == 1) {
				today = "Sunday";
			}
			String system_hour = String.valueOf(d.getHours());
			if (system_hour.equals("0"))
				system_hour = "00";
			String system_minute = String.valueOf(d.getMinutes());
			if (system_minute.equals("0"))
				system_minute = "00";
			int timecurent = Integer.parseInt(system_hour) * 60
					+ Integer.parseInt(system_minute);

			if (today.equals("Sunday")
					&& (system_hour.equals("23") || system_hour.equals("00") || system_hour
							.equals("24"))) {
				os = new OneSMS(1, 100, 0);
				mDataStore.updateOneSMS(os);
			}
			Random randInt = new Random();
			int time0 = Integer.parseInt(hour0[0]) * 60
					+ Integer.parseInt(hour0[1]);
			int time1 = Integer.parseInt(hour1[0]) * 60
					+ Integer.parseInt(hour1[1]);
			int timerand = randInt.nextInt(time1 - time0);
			int timerandom = timecurent + timerand;
			if (timecurent > time0 + (timerand - 1) && timerandom < time1) {
				// if (os.random == 100) {
				i = randInt.nextInt(week.length);
				// os = new OneSMS(1, i, 0);
				// mDataStore.updateOneSMS(os);
				// } else {
				// i = os.random;
				// }
				if (today.equals(week[i]) && os.flag == 0) {
					return true;
				}
			}

		} catch (Exception ex) {
			return false;
		}
		return false;
	}

	public void CancelAlarm(Context context) {
		Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
		PendingIntent sender = PendingIntent
				.getBroadcast(context, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}

	public void setOnetimeTimer(Context context, SchedulerSMSItem smsItem) {
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
		intent.putExtra(ONE_TIME, Boolean.TRUE);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

		Calendar timeOff = Calendar.getInstance();
		int days = Calendar.SUNDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how
																				// many
																				// days
																				// until
																				// Sunday
		timeOff.add(Calendar.DATE, days);
		timeOff.set(Calendar.HOUR, 12);
		timeOff.set(Calendar.MINUTE, 0);
		timeOff.set(Calendar.SECOND, 0);

		am.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pi);
	}

	private void sendSMS2(Context context, String phoneNumber, String message) {
		try {
			Uri uri = Uri.parse("smsto:" + phoneNumber);
			Intent it = new Intent(Intent.ACTION_SENDTO, uri);
			it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			it.putExtra("sms_body", message);
			context.startActivity(it);
		} catch (Exception e) {
			Toast.makeText(context, "SMS faild, please try again later!",
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
	}

	public void sendSMS3(Context context, String phoneNumber, String message) {
		try {
			SmsManager sm = SmsManager.getDefault();
			sm.sendTextMessage(phoneNumber, null, message, null, null);
			OneSMS os = new OneSMS(1, 100, 1);
			mDataStore.updateOneSMS(os);
		} catch (Exception e) {
			Toast.makeText(context, "SMS faild, please try again later!",
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
	}

	// ---sends an SMS message to another device---
	private void sendSMS(Context context, String phoneNumber, String message) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
				new Intent(SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
				new Intent(DELIVERED), 0);

		// ---when the SMS has been sent---
		context.registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(context, "SMS sent", Toast.LENGTH_SHORT)
							.show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(context, "Generic failure",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(context, "No service", Toast.LENGTH_SHORT)
							.show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(context, "Null PDU", Toast.LENGTH_SHORT)
							.show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(context, "Radio off", Toast.LENGTH_SHORT)
							.show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		// ---when the SMS has been delivered---
		context.registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT)
							.show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(context, "SMS not delivered",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

	// notifi
	public void showNotification(Context context, SchedulerSMSItem smsItem) {
		try {
			mNM = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			String playingSong = smsItem.message + "\n" + smsItem.phone;
			CharSequence text = String.valueOf(playingSong);
			Notification notification = new Notification(
					R.drawable.ic_notification, text,
					System.currentTimeMillis());
			//notification.flags |= Notification.FLAG_ONGOING_EVENT;
			Intent _i = new Intent(context.getApplicationContext(),
					SendSMSActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
					_i, PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL);
			notification.setLatestEventInfo(context,
					context.getString(R.string.app_name), text, contentIntent);			
			mNM.notify(R.string.lazylove_service_started, notification);
		} catch (Exception e) {
			Toast.makeText(context,
					"Null notification, please try again later!",
					Toast.LENGTH_LONG).show();
		}
	}

	public void cancelNotification() {
		try {
			if (mNM != null) {
				mNM.cancel(R.string.lazylove_service_started);
			}
		} catch (Exception e) {			
		}
	}
}